const fileCache = require('./fileCache');
const qianwenService = require('./qianwen');
const { MBTI_QUESTIONS, QUESTION_WEIGHTS, DIMENSION_DESCRIPTIONS, RESULT_TEMPLATES, QUESTION_ORDER } = require('../data/mbtiQuestions');

// MBTI类型特征描述
const TYPE_DESCRIPTIONS = {
  ISTJ: "检查者：实际、负责任、传统",
  ISFJ: "守护者：忠诚、体贴、传统",
  INFJ: "咨询师：理想主义、富有同情心、有创造力",
  INTJ: "建筑师：战略家、独立、创新",
  ISTP: "鉴赏家：灵活、实用、解决问题",
  ISFP: "探险家：艺术、敏感、自由",
  INFP: "调停者：理想主义、忠诚、有创造力",
  INTP: "逻辑学家：创新、分析、独立",
  ESTP: "企业家：灵活、实用、行动导向",
  ESFP: "表演者：热情、艺术、社交",
  ENFP: "竞选者：热情、创新、社交",
  ENTP: "辩论家：创新、分析、社交",
  ESTJ: "总经理：实际、负责任、传统",
  ESFJ: "执政官：忠诚、体贴、社交",
  ENFJ: "主人公：理想主义、富有同情心、社交",
  ENTJ: "指挥官：战略家、独立、社交"
};

// 职业匹配数据
const CAREER_MATCHES = {
  ISTJ: [
    { title: "会计", level: "高", description: "需要精确性和系统性的工作" },
    { title: "审计师", level: "高", description: "需要分析能力和责任心的职位" },
    { title: "项目经理", level: "中", description: "需要组织能力和执行力的工作" },
    { title: "系统分析师", level: "高", description: "需要逻辑思维和系统分析能力" },
    { title: "法律顾问", level: "中", description: "需要严谨和条理性的工作" },
    { title: "质量管理员", level: "高", description: "需要细致和规范性的工作" },
    { title: "金融分析师", level: "高", description: "需要数据分析和决策能力" },
    { title: "行政主管", level: "中", description: "需要组织和管理能力" }
  ],
  ISFJ: [
    { title: "护士", level: "高", description: "需要关怀和细心的职业" },
    { title: "教师", level: "高", description: "需要耐心和教导能力" },
    { title: "社工", level: "高", description: "需要同理心和服务精神" },
    { title: "人力资源专员", level: "中", description: "需要人际交往和协调能力" },
    { title: "行政助理", level: "高", description: "需要细致和条理性的工作" },
    { title: "客户服务代表", level: "中", description: "需要耐心和沟通能力" },
    { title: "图书管理员", level: "高", description: "需要细致和系统性的工作" },
    { title: "医疗记录员", level: "高", description: "需要准确性和条理性的工作" }
  ],
  INFJ: [
    { title: "心理咨询师", level: "高", description: "需要洞察力和同理心" },
    { title: "作家", level: "高", description: "需要创造力和表达能力" },
    { title: "教育顾问", level: "高", description: "需要指导能力和同理心" },
    { title: "人力资源经理", level: "中", description: "需要人际洞察力" },
    { title: "艺术治疗师", level: "高", description: "需要创造力和同理心" },
    { title: "非营利组织管理者", level: "中", description: "需要使命感和领导力" },
    { title: "职业顾问", level: "高", description: "需要洞察力和指导能力" },
    { title: "编辑", level: "中", description: "需要创造力和细致性" }
  ],
  INTJ: [
    { title: "科学家", level: "高", description: "需要创新思维和研究能力" },
    { title: "战略顾问", level: "高", description: "需要战略思维和分析能力" },
    { title: "系统架构师", level: "高", description: "需要系统思维和创新能力" },
    { title: "研究分析师", level: "高", description: "需要分析能力和创新思维" },
    { title: "大学教授", level: "中", description: "需要专业知识和教学能力" },
    { title: "投资分析师", level: "中", description: "需要分析能力和决策能力" },
    { title: "技术总监", level: "高", description: "需要技术领导力和战略思维" },
    { title: "管理顾问", level: "中", description: "需要分析能力和战略思维" }
  ],
  ISTP: [
    { title: "工程师", level: "高", description: "需要技术能力和问题解决能力" },
    { title: "机械师", level: "高", description: "需要动手能力和技术知识" },
    { title: "飞行员", level: "高", description: "需要技术能力和应变能力" },
    { title: "软件开发者", level: "中", description: "需要技术能力和逻辑思维" },
    { title: "法医", level: "高", description: "需要分析能力和技术知识" },
    { title: "建筑师", level: "中", description: "需要技术能力和创造力" },
    { title: "技术专家", level: "高", description: "需要专业知识和问题解决能力" },
    { title: "质量控制工程师", level: "中", description: "需要技术能力和分析能力" }
  ],
  ISFP: [
    { title: "艺术家", level: "高", description: "需要创造力和艺术感" },
    { title: "设计师", level: "高", description: "需要创造力和审美能力" },
    { title: "音乐家", level: "高", description: "需要艺术才能和表现力" },
    { title: "摄影师", level: "高", description: "需要艺术感和技术能力" },
    { title: "美容师", level: "中", description: "需要审美能力和服务意识" },
    { title: "厨师", level: "中", description: "需要创造力和技术能力" },
    { title: "园艺师", level: "高", description: "需要艺术感和实践能力" },
    { title: "手工艺人", level: "高", description: "需要创造力和技术能力" }
  ],
  INFP: [
    { title: "作家", level: "高", description: "需要创造力和表达能力" },
    { title: "心理咨询师", level: "高", description: "需要同理心和洞察力" },
    { title: "艺术治疗师", level: "高", description: "需要创造力和同理心" },
    { title: "编辑", level: "中", description: "需要创造力和细致性" },
    { title: "翻译", level: "中", description: "需要语言能力和文化理解" },
    { title: "教师", level: "中", description: "需要教导能力和同理心" },
    { title: "社工", level: "高", description: "需要同理心和服务精神" },
    { title: "职业顾问", level: "中", description: "需要洞察力和指导能力" }
  ],
  INTP: [
    { title: "科学家", level: "高", description: "需要创新思维和研究能力" },
    { title: "软件工程师", level: "高", description: "需要逻辑思维和技术能力" },
    { title: "大学教授", level: "高", description: "需要专业知识和教学能力" },
    { title: "研究分析师", level: "高", description: "需要分析能力和创新思维" },
    { title: "系统架构师", level: "中", description: "需要系统思维和创新能力" },
    { title: "哲学家", level: "高", description: "需要思考能力和表达能力" },
    { title: "数据分析师", level: "高", description: "需要分析能力和逻辑思维" },
    { title: "技术顾问", level: "中", description: "需要专业知识和问题解决能力" }
  ],
  ESTP: [
    { title: "企业家", level: "高", description: "需要行动力和决策能力" },
    { title: "销售经理", level: "高", description: "需要人际交往和说服能力" },
    { title: "运动员", level: "高", description: "需要运动能力和竞争意识" },
    { title: "警察", level: "中", description: "需要行动力和应变能力" },
    { title: "项目经理", level: "中", description: "需要执行力和管理能力" },
    { title: "市场营销专员", level: "中", description: "需要创造力和执行力" },
    { title: "活动策划师", level: "高", description: "需要组织能力和创造力" },
    { title: "房地产经纪人", level: "中", description: "需要人际交往和谈判能力" }
  ],
  ESFP: [
    { title: "演员", level: "高", description: "需要表现力和创造力" },
    { title: "活动策划师", level: "高", description: "需要组织能力和创造力" },
    { title: "销售代表", level: "高", description: "需要人际交往和说服能力" },
    { title: "旅游顾问", level: "高", description: "需要服务意识和沟通能力" },
    { title: "公关专员", level: "中", description: "需要人际交往和表达能力" },
    { title: "客户服务经理", level: "中", description: "需要服务意识和管理能力" },
    { title: "娱乐主持人", level: "高", description: "需要表现力和应变能力" },
    { title: "酒店经理", level: "中", description: "需要服务意识和管理能力" }
  ],
  ENFP: [
    { title: "创意总监", level: "高", description: "需要创造力和领导能力" },
    { title: "市场营销经理", level: "高", description: "需要创造力和管理能力" },
    { title: "公关经理", level: "高", description: "需要人际交往和创造力" },
    { title: "教师", level: "中", description: "需要教导能力和创造力" },
    { title: "人力资源顾问", level: "中", description: "需要人际洞察力和沟通能力" },
    { title: "职业顾问", level: "高", description: "需要洞察力和指导能力" },
    { title: "活动策划师", level: "高", description: "需要创造力和组织能力" },
    { title: "作家", level: "中", description: "需要创造力和表达能力" }
  ],
  ENTP: [
    { title: "企业家", level: "高", description: "需要创新思维和领导能力" },
    { title: "管理顾问", level: "高", description: "需要分析能力和战略思维" },
    { title: "律师", level: "高", description: "需要辩论能力和分析能力" },
    { title: "市场营销总监", level: "中", description: "需要创造力和管理能力" },
    { title: "战略规划师", level: "高", description: "需要战略思维和创新能力" },
    { title: "投资银行家", level: "中", description: "需要分析能力和决策能力" },
    { title: "政治顾问", level: "中", description: "需要战略思维和沟通能力" },
    { title: "创新总监", level: "高", description: "需要创新思维和领导能力" }
  ],
  ESTJ: [
    { title: "项目经理", level: "高", description: "需要组织能力和执行力" },
    { title: "财务经理", level: "高", description: "需要管理能力和分析能力" },
    { title: "运营总监", level: "高", description: "需要管理能力和执行力" },
    { title: "行政主管", level: "高", description: "需要组织能力和管理能力" },
    { title: "销售经理", level: "中", description: "需要管理能力和执行力" },
    { title: "质量控制经理", level: "高", description: "需要管理能力和分析能力" },
    { title: "人力资源经理", level: "中", description: "需要管理能力和人际交往能力" },
    { title: "业务分析师", level: "中", description: "需要分析能力和管理能力" }
  ],
  ESFJ: [
    { title: "人力资源经理", level: "高", description: "需要人际交往和管理能力" },
    { title: "客户服务经理", level: "高", description: "需要服务意识和管理能力" },
    { title: "教师", level: "高", description: "需要教导能力和同理心" },
    { title: "活动策划师", level: "中", description: "需要组织能力和创造力" },
    { title: "公关经理", level: "中", description: "需要人际交往和沟通能力" },
    { title: "销售经理", level: "中", description: "需要人际交往和管理能力" },
    { title: "行政主管", level: "高", description: "需要组织能力和管理能力" },
    { title: "客户关系经理", level: "高", description: "需要服务意识和管理能力" }
  ],
  ENFJ: [
    { title: "人力资源总监", level: "高", description: "需要领导能力和人际洞察力" },
    { title: "教育顾问", level: "高", description: "需要指导能力和同理心" },
    { title: "非营利组织管理者", level: "高", description: "需要使命感和领导能力" },
    { title: "公关总监", level: "高", description: "需要领导能力和沟通能力" },
    { title: "职业顾问", level: "高", description: "需要洞察力和指导能力" },
    { title: "培训经理", level: "高", description: "需要教导能力和管理能力" },
    { title: "团队领导", level: "高", description: "需要领导能力和人际交往能力" },
    { title: "组织发展顾问", level: "中", description: "需要领导能力和战略思维" }
  ],
  ENTJ: [
    { title: "首席执行官", level: "高", description: "需要领导能力和战略思维" },
    { title: "管理顾问", level: "高", description: "需要战略思维和分析能力" },
    { title: "投资银行家", level: "高", description: "需要分析能力和决策能力" },
    { title: "企业家", level: "高", description: "需要领导能力和创新思维" },
    { title: "战略规划总监", level: "高", description: "需要战略思维和领导能力" },
    { title: "运营总监", level: "高", description: "需要管理能力和执行力" },
    { title: "项目经理", level: "中", description: "需要管理能力和执行力" },
    { title: "业务发展总监", level: "高", description: "需要战略思维和领导能力" }
  ]
};

// 定义测试状态常量
const TEST_STATUS = {
  NOT_STARTED: 'not_started',
  IN_PROGRESS: 'in_progress',
  COMPLETED: 'completed'
};

// 获取测试状态
async function getTestStatus(sessionId) {
  console.log(`[getTestStatus] 开始获取测试状态, sessionId: ${sessionId}`);
  
  const status = await fileCache.getCard('mbti_test', { query: sessionId });
  console.log(`[getTestStatus] 缓存查询结果:`, status ? '找到缓存' : '缓存未找到');
  
  if (!status) {
    console.log(`[getTestStatus] 缓存未找到，返回默认状态: NOT_STARTED`);
    return {
      status: TEST_STATUS.NOT_STARTED,
      currentQuestion: 1,
      totalQuestions: MBTI_QUESTIONS.length,
      answeredQuestions: 0,
      lastAnswerTime: null
    };
  }
  
  // 获取已回答的问题数量
  const answers = await fileCache.getCard('mbti_answers', { query: sessionId }) || { content: [] };
  console.log(`[getTestStatus] 答案缓存查询结果:`, answers ? `找到${answers.content.length}个答案` : '答案缓存未找到');
  
  const result = {
    ...status.content,
    answeredQuestions: answers.content.length,
    totalQuestions: MBTI_QUESTIONS.length
  };
  
  console.log(`[getTestStatus] 返回状态:`, {
    status: result.status,
    currentQuestion: result.currentQuestion,
    answeredQuestions: result.answeredQuestions,
    totalQuestions: result.totalQuestions
  });
  
  return result;
}

// 开始测试
async function startTest(sessionId) {
  try {
    // 先检查是否已经有进行中的测试
    const existingStatus = await getTestStatus(sessionId);
    if (existingStatus.status === TEST_STATUS.IN_PROGRESS) {
      console.log('测试已经在进行中，返回当前状态');
      return existingStatus;
    }

    const status = {
      status: TEST_STATUS.IN_PROGRESS,
      currentQuestion: 1,
      totalQuestions: MBTI_QUESTIONS.length,
      answeredQuestions: 0,
      startTime: new Date().toISOString(),
      lastAnswerTime: null
    };
    
    // 保存状态到缓存
    try {
      await fileCache.saveCard('mbti_test', { query: sessionId }, {
        type: 'mbti_test',
        content: status
      });

      // 确保答案缓存被清空
      await fileCache.saveCard('mbti_answers', { query: sessionId }, {
        type: 'mbti_answers',
        content: []
      });

      // 等待一小段时间确保文件写入完成
      await new Promise(resolve => setTimeout(resolve, 100));

      // 验证状态是否被正确保存
      const savedStatus = await fileCache.getCard('mbti_test', { query: sessionId });
      if (!savedStatus) {
        throw new Error('测试状态保存失败：缓存未找到');
      }
      if (!savedStatus.content || savedStatus.content.status !== TEST_STATUS.IN_PROGRESS) {
        throw new Error('测试状态保存失败：状态不正确');
      }

      // 再次验证答案缓存是否被清空
      const answersCache = await fileCache.getCard('mbti_answers', { query: sessionId });
      if (!answersCache || !Array.isArray(answersCache.content) || answersCache.content.length > 0) {
        throw new Error('答案缓存清空失败');
      }

      console.log('测试状态保存成功:', savedStatus);
      return savedStatus.content;
    } catch (error) {
      console.error('保存测试状态失败:', error);
      throw new Error(`保存测试状态失败: ${error.message}`);
    }
  } catch (error) {
    console.error('开始测试失败:', error);
    throw new Error(`开始测试失败: ${error.message}`);
  }
}

// 更新测试状态
async function updateTestStatus(sessionId, questionNumber) {
  const statusData = await fileCache.getCard('mbti_test', { query: sessionId }) || {
    content: {
      status: TEST_STATUS.IN_PROGRESS,
      startTime: new Date().toISOString(),
      currentQuestion: 1,
      totalQuestions: MBTI_QUESTIONS.length  // 确保使用正确的总题目数
    }
  };
  
  const status = statusData.content;
  // 确保问题编号不超过总问题数
  status.currentQuestion = Math.min(questionNumber + 1, status.totalQuestions);
  status.lastAnswerTime = new Date().toISOString();
  
  // 获取已回答的问题数量
  const answersData = await fileCache.getCard('mbti_answers', { query: sessionId }) || { content: [] };
  status.answeredQuestions = answersData.content.length;
  
  // 检查是否完成所有问题
  if (status.answeredQuestions >= status.totalQuestions) {
    console.log('[updateTestStatus] 所有问题已回答，更新状态为已完成');
    status.status = TEST_STATUS.COMPLETED;
    status.currentQuestion = status.totalQuestions;  // 确保当前问题编号正确
  }
  
  console.log('[updateTestStatus] 更新后的状态:', {
    status: status.status,
    currentQuestion: status.currentQuestion,
    answeredQuestions: status.answeredQuestions,
    totalQuestions: status.totalQuestions
  });
  
  await fileCache.saveCard('mbti_test', { query: sessionId }, {
    type: 'mbti_test',
    content: status
  });
  return status;
}

// 重置测试
async function resetTest(sessionId) {
  // 由于 fileCache 没有直接的删除方法，我们可以通过保存空数据来模拟删除
  await fileCache.saveCard('mbti_test', { query: sessionId }, {
    type: 'mbti_test',
    content: null
  });
  await fileCache.saveCard('mbti_answers', { query: sessionId }, {
    type: 'mbti_answers',
    content: []
  });
  
  return startTest(sessionId);
}

// 获取下一个问题
const getNextQuestion = async (sessionId, currentQuestionNumber, answers) => {
  // 获取测试状态
  const testStatus = await getTestStatus(sessionId);
  console.log('[getNextQuestion] 获取到的测试状态:', testStatus);
  
  if (testStatus.status !== TEST_STATUS.IN_PROGRESS) {
    throw new Error('测试未开始或已结束');
  }

  // 获取所有问题
  const allQuestions = MBTI_QUESTIONS;
  const totalQuestions = allQuestions.length;
  console.log('[getNextQuestion] 总问题数量:', totalQuestions);

  // 获取已回答的问题ID列表
  const answeredQuestionIds = answers.map(a => a.questionId);
  console.log('[getNextQuestion] 已回答的问题ID:', answeredQuestionIds);
  console.log('[getNextQuestion] 当前问题编号:', currentQuestionNumber);

  // 检查是否已经回答了所有问题
  if (answeredQuestionIds.length >= totalQuestions || currentQuestionNumber >= totalQuestions) {
    console.log('[getNextQuestion] 所有问题已回答或已达到最大问题数，测试完成');
    return {
      type: 'mbti_result',
      status: TEST_STATUS.COMPLETED,
      currentQuestion: totalQuestions,
      totalQuestions: totalQuestions,
      answeredQuestions: answeredQuestionIds.length
    };
  }

  // 确保当前问题编号不超过总问题数
  if (currentQuestionNumber >= totalQuestions) {
    console.log('[getNextQuestion] 当前问题编号超出范围，返回完成状态');
    return {
      type: 'mbti_result',
      status: TEST_STATUS.COMPLETED,
      currentQuestion: totalQuestions,
      totalQuestions: totalQuestions,
      answeredQuestions: answeredQuestionIds.length
    };
  }

  let question = null;

  try {
    // 临时修改：只使用前3个问题
    question = allQuestions[currentQuestionNumber];
    if (!question) {
      console.error(`[getNextQuestion] 未找到问题 ID ${currentQuestionNumber + 1}`);
      throw new Error(`未找到问题 ID ${currentQuestionNumber + 1}`);
    }
    console.log(`[getNextQuestion] 找到问题:`, {
      id: question.id,
      dimension: question.dimension
    });

    // 更新测试状态
    await updateTestStatus(sessionId, currentQuestionNumber);

    // 返回问题对象，包含状态信息
    const result = {
      ...question,
      status: TEST_STATUS.IN_PROGRESS,
      currentQuestion: currentQuestionNumber + 1,
      totalQuestions: totalQuestions,
      answeredQuestions: answeredQuestionIds.length
    };
    
    console.log('[getNextQuestion] 返回问题结果:', {
      questionId: result.id,
      dimension: result.dimension,
      currentQuestion: result.currentQuestion,
      totalQuestions: result.totalQuestions,
      answeredQuestions: result.answeredQuestions
    });
    
    return result;
  } catch (error) {
    console.error('[getNextQuestion] 获取下一个问题时发生错误:', error);
    throw error;
  }
};

// 获取问题权重
const getQuestionWeight = (questionId, dimension) => {
  const weights = QUESTION_WEIGHTS[dimension];
  if (!weights) return 1.0;

  if (weights.high.includes(questionId)) return 1.5;
  if (weights.medium.includes(questionId)) return 1.2;
  if (weights.low.includes(questionId)) return 0.8;
  return 1.0;
};

// 计算维度得分
const calculateDimensionScore = (answers, dimension) => {
  const dimensionAnswers = answers.filter(a => {
    const question = MBTI_QUESTIONS.find(q => q.id === a.questionId);
    return question && question.dimension === dimension;
  });

  if (dimensionAnswers.length === 0) return { [dimension[0]]: 0, [dimension[1]]: 0 };

  let score1 = 0;  // 第一个维度的得分
  let score2 = 0;  // 第二个维度的得分
  let weight1 = 0; // 第一个维度的权重总和
  let weight2 = 0; // 第二个维度的权重总和

  for (const answer of dimensionAnswers) {
    const question = MBTI_QUESTIONS.find(q => q.id === answer.questionId);
    if (!question) continue;

    // 将李克特量表答案转换为数值
    const value = convertLikertToValue(answer.answer);
    // 处理反向计分
    const effectiveValue = question.isReversed ? 6 - value : value;
    
    // 获取问题权重
    const weight = getQuestionWeight(question.id, dimension);
    
    // 根据问题维度分配得分
    if (question.dimension === dimension) {
      // 根据答案值判断偏向哪个维度
      // 1-2分偏向第二个维度，4-5分偏向第一个维度，3分不偏向任何维度
      if (effectiveValue >= 4) {
        score1 += effectiveValue * weight;
        weight1 += weight;
      } else if (effectiveValue <= 2) {
        score2 += (6 - effectiveValue) * weight; // 反向计算第二个维度的得分
        weight2 += weight;
      }
    }
  }

  // 计算加权平均得分
  const avgScore1 = weight1 > 0 ? score1 / weight1 : 0;
  const avgScore2 = weight2 > 0 ? score2 / weight2 : 0;

  return {
    [dimension[0]]: avgScore1,
    [dimension[1]]: avgScore2
  };
};

// 计算答案一致性
const calculateAnswerConsistency = (answers, dimension) => {
  const dimensionAnswers = answers.filter(a => {
    const question = MBTI_QUESTIONS.find(q => q.id === a.questionId);
    return question && question.dimension === dimension;
  });

  if (dimensionAnswers.length < 2) return 1;

  // 计算答案之间的相关性
  let consistency = 0;
  let pairs = 0;

  for (let i = 0; i < dimensionAnswers.length; i++) {
    for (let j = i + 1; j < dimensionAnswers.length; j++) {
      const q1 = MBTI_QUESTIONS.find(q => q.id === dimensionAnswers[i].questionId);
      const q2 = MBTI_QUESTIONS.find(q => q.id === dimensionAnswers[j].questionId);
      
      if (!q1 || !q2) continue;

      const v1 = convertLikertToValue(dimensionAnswers[i].answer);
      const v2 = convertLikertToValue(dimensionAnswers[j].answer);
      
      // 考虑问题是否反向计分
      const effectiveV1 = q1.isReversed ? 6 - v1 : v1;
      const effectiveV2 = q2.isReversed ? 6 - v2 : v2;
      
      // 计算答案差异
      const diff = Math.abs(effectiveV1 - effectiveV2);
      consistency += 1 - (diff / 4); // 归一化到 [0, 1]
      pairs++;
    }
  }

  return pairs > 0 ? consistency / pairs : 1;
};

// 将李克特量表答案转换为数值
const convertLikertToValue = (answer) => {
  const values = {
    '非常符合': 5,
    '比较符合': 4,
    '一般': 3,
    '不太符合': 2,
    '完全不符合': 1
  };
  return values[answer] || 3;
};

// 存储答案
async function saveAnswer(sessionId, questionNumber, answer) {
  const answersData = await fileCache.getCard('mbti_answers', { query: sessionId }) || { content: [] };
  let answers = answersData.content;
  
  // 更新或添加答案
  const answerIndex = answers.findIndex(a => a.questionId === questionNumber);
  if (answerIndex >= 0) {
    answers[answerIndex] = {
      questionId: questionNumber,
      answer,
      timestamp: new Date().toISOString()
    };
  } else {
    answers.push({
      questionId: questionNumber,
      answer,
      timestamp: new Date().toISOString()
    });
  }
  
  // 按问题ID排序
  answers.sort((a, b) => a.questionId - b.questionId);
  
  await fileCache.saveCard('mbti_answers', { query: sessionId }, {
    type: 'mbti_answers',
    content: answers
  });
  await updateTestStatus(sessionId, questionNumber);
  
  return {
    answers,
    status: await getTestStatus(sessionId)
  };
}

// 计算MBTI类型
async function calculateMBTIType(sessionId) {
  const status = await getTestStatus(sessionId);
  if (status.status !== TEST_STATUS.COMPLETED) {
    throw new Error('测试未完成');
  }
  
  const answersData = await fileCache.getCard('mbti_answers', { query: sessionId });
  
  if (!answersData || !answersData.content || answersData.content.length < status.totalQuestions) {
    throw new Error('测试未完成');
  }

  const answers = answersData.content;

  // 计算维度得分
  const dimensionScores = {};
  for (const dimension of ['EI', 'SN', 'TF', 'JP']) {
    dimensionScores[dimension] = calculateDimensionScore(answers, dimension);
    console.log(`维度 ${dimension} 得分:`, dimensionScores[dimension]);
  }

  // 确定MBTI类型
  const mbtiType = Object.entries(dimensionScores).map(([dimension, scores]) => {
    const [type1, type2] = dimension.split('');
    const score1 = scores[type1];
    const score2 = scores[type2];
    console.log(`维度 ${dimension} 最终判断:`, {
      type1, score1,
      type2, score2,
      result: score1 > score2 ? type1 : type2
    });
    return score1 > score2 ? type1 : type2;
  }).join('');

  console.log('最终MBTI类型:', mbtiType);

  // 生成详细报告
  const report = {
    type: mbtiType,
    description: TYPE_DESCRIPTIONS[mbtiType] || '未找到类型描述',
    dimensions: {},
    analysis: {
      strengths: [],
      challenges: [],
      development: [],
      career: []
    }
  };

  // 为每个维度生成详细分析
  Object.entries(dimensionScores).forEach(([dimension, scores]) => {
    const [type1, type2] = dimension.split('');
    const dominant = scores[type1] > scores[type2] ? type1 : type2;
    
    report.dimensions[dimension] = {
      dominant,
      scores: {
        raw: scores,
        weighted: calculateWeightedScores(scores, dimension),
        percentage: {
          [type1]: (scores[type1] / (scores[type1] + scores[type2])) * 100,
          [type2]: (scores[type2] / (scores[type1] + scores[type2])) * 100
        }
      },
      analysis: {
        content: `在${dimension}维度上，您更倾向于${dominant}类型。`,
        suggestions: []
      }
    };
  });

  // 生成整体分析
  report.analysis = {
    strengths: {
      title: "优势特点",
      items: [TYPE_DESCRIPTIONS[mbtiType] || "未找到类型描述"]
    },
    challenges: {
      title: "潜在挑战",
      items: ["建议根据个人情况调整"]
    },
    development: {
      title: "发展建议",
      items: ["建议根据个人情况调整"]
    },
    career: {
      title: "职业建议",
      items: ["建议根据个人情况调整"]
    }
  };

  // 保存结果
  await fileCache.saveCard('mbti_result', { query: sessionId }, {
    type: 'mbti_result',
    content: report
  });
  
  return report;
}

// 计算加权得分
function calculateWeightedScores(scores, dimension) {
  // 简化权重计算，直接使用原始得分
  return {
    [dimension[0]]: scores[dimension[0]],
    [dimension[1]]: scores[dimension[1]]
  };
}

// 计算百分比得分
function calculatePercentageScores(scores) {
  const total = scores[Object.keys(scores)[0]] + 
                scores[Object.keys(scores)[1]];
  return {
    [Object.keys(scores)[0]]: (scores[Object.keys(scores)[0]] / total) * 100,
    [Object.keys(scores)[1]]: (scores[Object.keys(scores)[1]] / total) * 100
  };
}

// 计算子维度得分
function calculateSubDimensionScore(answers, dimension, subDimension) {
  const relevantQuestions = MBTI_QUESTIONS.filter(q => 
    q.dimension === dimension && q.subDimension === subDimension
  );
  
  let score = 0;
  relevantQuestions.forEach(q => {
    const answer = answers[q.id];
    if (answer) {
      const effectiveAnswer = q.isReversed ? (5 - answer) : answer;
      score += (effectiveAnswer - 3) * (q.weight || 1.0);
    }
  });
  
  return score / relevantQuestions.length;
}

// 生成维度分析
function generateDimensionAnalysis(dimension, dominant, scores) {
  const description = DIMENSION_DESCRIPTIONS[dimension];
  const template = RESULT_TEMPLATES.dimension;
  
  return {
    content: template.description
      .replace('{name}', description.name)
      .replace('{value}', dominant)
      .replace('{description}', description.description),
    suggestions: generateDimensionSuggestions(dimension, dominant, scores)
  };
}

// 生成整体分析
function generateOverallAnalysis(dimensions, mbtiType) {
  const typeInfo = MBTI_TYPES[mbtiType];
  const template = RESULT_TEMPLATES.type;
  
  return {
    strengths: {
      title: template.strengths.title,
      items: typeInfo.strengths.map(s => 
        template.strengths.items[0].replace('{strength1}', s)
      )
    },
    challenges: {
      title: template.challenges.title,
      items: typeInfo.challenges.map(c => 
        template.challenges.items[0].replace('{challenge1}', c)
      )
    },
    development: {
      title: template.development.title,
      items: generateDevelopmentSuggestions(dimensions)
    },
    career: {
      title: template.career.title,
      items: typeInfo.careerMatches.map(c => 
        template.career.items[0].replace('{career1}', c)
      )
    }
  };
}

// 生成职业匹配分析
async function generateCareerAnalysis(mbtiType, careerPreferences = []) {
  // 获取基础职业匹配
  const baseMatches = CAREER_MATCHES[mbtiType] || [];
  
  // 使用千问API生成更详细的职业分析
  const prompt = `基于MBTI类型${mbtiType}，请生成一份详细的职业匹配分析报告。

要求：
1. 分析该MBTI类型的性格特征
2. 推荐3-5个最适合的职业方向
3. 对每个推荐职业提供：
   - 职业描述
   - 所需技能
   - 发展前景
   - 潜在挑战
4. 提供职业发展建议

用户职业偏好：${careerPreferences.join(', ') || '无特定偏好'}

请以JSON格式返回，包含以下字段：
{
  "personalityTraits": [
    {
      "title": "特征标题",
      "description": "特征描述"
    }
  ],
  "careerMatches": [
    {
      "title": "职业名称",
      "level": "匹配度（高/中/低）",
      "description": "职业描述",
      "requiredSkills": ["技能1", "技能2"],
      "prospects": "发展前景",
      "challenges": "潜在挑战"
    }
  ],
  "developmentSuggestions": [
    {
      "title": "建议标题",
      "description": "建议内容"
    }
  ]
}`;

  try {
    const response = await qianwenService.generateContent(prompt);
    const analysis = JSON.parse(response);
    
    // 合并基础匹配和AI生成的详细分析
    return {
      personalityTraits: analysis.personalityTraits,
      careerMatches: analysis.careerMatches.map(match => ({
        ...match,
        baseMatch: baseMatches.find(bm => bm.title === match.title)?.level || '未知'
      })),
      developmentSuggestions: analysis.developmentSuggestions
    };
  } catch (error) {
    console.error('生成职业分析失败:', error);
    // 如果AI生成失败，返回基础匹配
    return {
      personalityTraits: [{
        title: "基础性格特征",
        description: TYPE_DESCRIPTIONS[mbtiType]
      }],
      careerMatches: baseMatches,
      developmentSuggestions: [{
        title: "基础发展建议",
        description: "建议根据个人兴趣和实际情况选择职业方向"
      }]
    };
  }
}

module.exports = {
  startTest,
  resetTest,
  getTestStatus,
  getNextQuestion,
  calculateMBTIType,
  saveAnswer,
  generateCareerAnalysis,
  TEST_STATUS
}; 